import React, {useEffect, useMemo, useState} from 'react';
import {Menu, Layout, MenuProps} from "antd";
import {useLocation, useNavigate} from "react-router-dom";
import {renderSlider} from "@/routes";
import {getInfoAsync} from "@/store/slices/auth";

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}

// const items: MenuItem[] = [
//     getItem('主页', '/', <HomeOutlined />),
//     getItem('数据管理', '/cmn', <DatabaseOutlined />, [
//         getItem('数据字典', '/cmn/dict')
//     ])
// ];


function IndexSider() {
    const navigate = useNavigate();
    const {pathname} = useLocation();
    const [collapsed,setCollapsed] = useState(false);
    const [key,setKey] = useState("/");// 选中subMenu的key值
    // [
    //      getItem("主页","/",<HomeOutlined />),
    //      getItem("数据管理","/cmn",<DatabaseOutlined />)
    // ]
    const items:MenuItem[] = useMemo(function(){
        return (
            renderSlider().map((item:any)=>{
                let subMenu;
                if(item.children){
                    subMenu = item.children.filter((v:any)=>!v.isHide).map((item:any)=>(
                        getItem(item.label,item.path)
                    ))
                }
                return getItem(item.label,item.path,item.icon,subMenu);
            })
        )
    },[])


    useEffect(()=>{
        setKey("/"+pathname.split("/")[1])
    },[pathname])
    return (
        <Layout.Sider breakpoint={"md"} collapsible collapsed={collapsed} onCollapse={value => setCollapsed(value)}>
            <div className="logo">
                <img src={require("@/assets/img/logo.png")} alt=""/>
                <span style={{display:collapsed?"none":"inline-block"}}>尚医通管理系统</span>
            </div>
            <Menu onClick={({key})=>{
                // 点击 MenuItem 调用此函数
                navigate(key);
            }} theme="dark"
                  // 当前展开的 SubMenu 菜单项 key 数组
                  openKeys={[key]}
                  // SubMenu 展开/关闭的回调
                  onOpenChange={(openKeys: string[])=>{
                      setKey(openKeys[1])
                  }}
                  // 初始选中的菜单项 key 数组
                  defaultSelectedKeys={[pathname]}
                  mode="inline" items={items} />
        </Layout.Sider>
    );
}

export default IndexSider;